package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {

	/**
	 * Programme implementant un echo a travers des sockets entre un client et
	 * un serveur. Celui-ci est le serveur.
	 * @param args
	 */
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(4444);
			System.out.println("Started Echo server");
		} catch (IOException e) {
			System.out.println("Could not listen on port: 4444");
			System.exit(-1);
		}
		Socket clientSocket = null;

		try {
			clientSocket = serverSocket.accept();
			System.out.println("Accepted client : "
					+ clientSocket.getInetAddress());
		} catch (IOException e) {
			System.out.println("Accept failed: 4444");
			System.exit(-1);
		}
		PrintWriter out = null;
		BufferedReader in = null;
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(
				System.in)); 
		try {
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(clientSocket
					.getInputStream()));
			String inputLine, outputLine;
			while ((inputLine = in.readLine()) != null) {
				System.out.println("client : " + inputLine);
				
				outputLine = stdIn.readLine();
				out.println(outputLine);
				
				if (outputLine.equalsIgnoreCase("Bye.")) {
					System.out.println("Server sent or received bye. Quitting.");
					break;
				}
			}
		} catch (IOException ioe) {
			System.out.println("Could not open out or in IO on client socket");
			System.exit(-1);
		}

	}

}
